<script setup>
import { onMounted } from 'vue'
import { fabric } from 'fabric'
onMounted(() => {
  // 使用id为canvas是的画板生成一个fabricCanvas
  const canvas = new fabric.Canvas('canvas', { width: 1200, height: 800 });
  canvas.isDrawingMode = true; // 绘画一定有要设置isDrawingMode为true
  let isDrawing = false; // 是否处于绘画状态
  let path = null; // 画的路径

  canvas.on('mouse:down', event => {
    // 创建路径对象
    const pointer = canvas.getPointer(event.e);
    path = new fabric.Path(`M ${pointer.x} ${pointer.y}`, {
      stroke: 'red',
      strokeWidth: 30,
      fill: 'transparent'
    });
    canvas.add(path);

    // 开始绘制
    isDrawing = true;
  });

  // 监听鼠标移动事件
  canvas.on('mouse:move', event => {
    if (!isDrawing) return;
    // 更新路径
    const pointer = canvas.getPointer(event.e);
    const pathData = `${path.path[0][1]} ${path.path[0][2]} L ${pointer.x} ${pointer.y}`;
    path.set({ d: pathData });
    canvas.renderAll();
  });

  // 监听鼠标松开事件
  canvas.on('mouse:up', () => {
    isDrawing = false;
  });
});

</script>

<template>
  <canvas id="canvas"></canvas>
</template>

<style scoped>
#canvas {
  margin: 10px;
  border: 1px solid #d3d3d3;
}
</style>